package com.hjy.websocket.config;

import com.hjy.exception.CfmsErrorType;
import com.hjy.exception.CfmsException;
import com.hjy.websocket.domain.WsClassData;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
public class AnnotationScanner {

    private final ApplicationContext applicationContext;
    private static Map<String, WsClassData> classesResult = new HashMap<>();

    public AnnotationScanner(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void scan() {
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);
            Class<?> aClass = bean.getClass();
            // 获取类中所有的方法，包括继承的方法
            Method[] methods = aClass.getDeclaredMethods();
            for (Method method : methods) {
                // 检查方法是否有 WsAnnotation 注解
                if (method.isAnnotationPresent(WsAnnotation.class)) {
                    WsAnnotation annotation = method.getAnnotation(WsAnnotation.class);
                    String value = annotation.value();
                    if (classesResult.get(value) != null) {
                        throw new CfmsException(CfmsErrorType.ERROR_INTERNAL_ERROR, "当前websocket请求名称已使用： " + value);
                    }
                    WsClassData wsClassData = new WsClassData();
                    wsClassData.setBean(bean);
                    wsClassData.setMethod(method);
                    classesResult.put(value, wsClassData);

                }
            }
        }
    }

    public static Map<String,WsClassData> getClassesResult() {
        return classesResult;
    }


}